package com.shixi.shixitraining.shixitraining.base;

import android.app.Activity;
import android.app.Application;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;

/**
 * Created by shenyan on 2018/7/5.
 */

public class App extends Application {

    public static App mApp;

    public static Application sAndroidApp;
    private List<Activity> mActivity = Collections.synchronizedList(new LinkedList<Activity>());

    @Override
    public void onCreate() {
        super.onCreate();
        mApp = this;
        sAndroidApp = this;
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.readTimeout(2000, TimeUnit.MILLISECONDS);
        builder.writeTimeout(1000, TimeUnit.MILLISECONDS);
        builder.connectTimeout(1000, TimeUnit.MILLISECONDS);

        OkGo.getInstance()
                .init(this)
                .setOkHttpClient(builder.build())
                .setCacheMode(CacheMode.NO_CACHE)
                .setRetryCount(3);

    }


    /*
     * 获取上下文
     * */
    public synchronized static Application getInstance() {
        return mApp;
    }

    /**
     * activity的任务栈
     *
     * @return
     */
    public List<Activity> getActivityList() {
        return mActivity;
    }

    public boolean contains(Activity activity) {
        return mActivity.contains(activity);
    }

    public void addActivity(Activity activity) {
        mActivity.add(activity);
    }

    public void removeActivity(Activity activity) {
        if (mActivity != null & mActivity.size() > 0) {
            mActivity.remove(activity);
        }
    }


    public void finshAllActivity(Activity activity) {
        if (mActivity == null || mActivity.isEmpty()) {
            return;
        }

        if (mActivity != null) {
            mActivity.remove(activity);
            activity.finish();
        }
    }

    public void finshAllActivity() {
        if (mActivity == null) {
            return;
        }

        for (Activity activity : mActivity) {
            if (activity != null) {
                activity.finish();
            }
        }
        mActivity.clear();
    }

    //退出app 销毁activity
    public void exit() {
        if (mActivity == null || mActivity.size() == 0) {
            return;
        }
        finshAllActivity();
        Runtime.getRuntime().gc();
        System.gc();
        System.exit(0);
    }


}
